package com.example.testapp.activity.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.testapp.R;
import com.example.testapp.activity.activity.study.AddCityActivity;
import com.example.testapp.activity.activity.study.WeaterMainActivity;
import com.example.testapp.activity.dabastate.SQLiteCityManager;
import com.example.testapp.activity.model.CityManagerEntity;
import com.example.testapp.activity.view.CHImageView;

import java.util.List;

/**
 * Created by l on 2016/8/2.
 */
public class CityManagerFragment extends Fragment {

    public static final String TAG = "CityManager";

    public FragmentAnd fragmentAnd;
    private View baseView;
    private GridView  mGridView;
    private CityManagerEntity cmb;
    private CityManagerAdapter mAdapter;
    private SQLiteCityManager  sqlite;
    private SQLiteDatabase  database;

    private String cityname;
    private String imageurl;
    private String weather;
    private String temp;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        fragmentAnd = (FragmentAnd) activity;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        WeaterMainActivity.TAG_H = TAG;
        baseView = inflater.inflate(R.layout.fragment_citymanager, container, false);
        initView();
        return baseView;
    }

    private void initView() {
        mGridView = (GridView)baseView.findViewById(R.id.gridview);
        final Intent intent = new Intent(getActivity(), AddCityActivity.class);
        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                 if(position == HomePageFragment.mcmb.size() - 1){
                      startActivity(intent);
                 }else{
                     fragmentAnd.showDialog();
                     WeaterMainActivity ff = (WeaterMainActivity) getActivity();
                     ff.switchFragment(WeaterMainActivity.homecontent, HomePageFragment.TAG);
                    // 得到城市，发起网络请求。
                    fragmentAnd.sendcitytext(HomePageFragment.mcmb.get(position).getCity());
                 }
            }
        });
        mAdapter = new CityManagerAdapter(getActivity(), HomePageFragment.mcmb);
        mGridView.setAdapter(mAdapter);
    }

    @Override
    public void onResume() {
        getdatabase();
        for (int i = 0; i < HomePageFragment.mcmb.size(); i++){
            if(HomePageFragment.mcmb.get(i).getCity().equals(WeaterMainActivity.cmb2.getCity())){
                HomePageFragment.mcmb.remove(WeaterMainActivity.cmb2);
            }
        }
       // 标记，为每次打开城市管理页都会加载一个item问题的解决方案
       WeaterMainActivity.cmb2.setCity("添加");
       HomePageFragment.mcmb.add(HomePageFragment.mcmb.size(), WeaterMainActivity.cmb2);
       mAdapter.setCitymanager(HomePageFragment.mcmb);
       for (int i = 0; i < HomePageFragment.mcmb.size(); i++){
           Log.i("TAG", HomePageFragment.mcmb.get(i).getCity());
       }
        Log.i("TAG", HomePageFragment.mcmb.size()+"<<<<==>>>>HomePageFragment.mcmb");
        mAdapter.notifyDataSetChanged();
        super.onResume();
    }

    private void getdatabase() {
        sqlite = new SQLiteCityManager(getActivity(), "weatherdb", null, 1);
        database = sqlite.getWritableDatabase();

        Cursor cursor = database.query("coolWeather", null, null, null, null, null, null);
        HomePageFragment.mcmb.clear();

        while (cursor.moveToNext()){
            int _id = cursor.getInt(cursor.getColumnIndex("_id"));
            cityname = cursor.getString(cursor.getColumnIndex("cityname"));
            imageurl = cursor.getString(cursor.getColumnIndex("imageurl"));
            weather = cursor.getString(cursor.getColumnIndex("weather"));
            temp = cursor.getString(cursor.getColumnIndex("temp"));
            Log.i("TAG", _id + "  @@@@@@@@_id-" + " cityname-" + cityname + " imageurl-"
                    + imageurl + " weather-" + weather + " temp-" + temp);
            setCityManagerEntity();
        }
    }

    private void setCityManagerEntity() {
        cmb = new CityManagerEntity();
        cmb.setCity(cityname);
        cmb.setWeather(weather);
        cmb.setTemp(temp);
        cmb.setWeatherimage(imageurl);
        for (int i = 0; i< HomePageFragment.mcmb.size(); i++){
            Log.i("TAG", HomePageFragment.mcmb.size()+"==>HomePageFragment.mcmb.size()");
            Log.i("TAG", HomePageFragment.mcmb.get(i).getCity()+"==>" +
                    "HomePageFragment.mcmb.get(i).getCity()");
            if(HomePageFragment.mcmb.get(i).getCity().equals(cmb.getCity())){
                HomePageFragment.mcmb.set(i, cmb);
                return;
            }
        }
        HomePageFragment.mcmb.add(cmb);
    }

    public class CityManagerAdapter extends BaseAdapter{

        private LayoutInflater mInflater;
        private List<CityManagerEntity> citymanager;
        private Context  context;
        private Dialog   mDialog;

        public CityManagerAdapter(Context context, List<CityManagerEntity> citymanager) {
            this.context = context;
            this.citymanager = citymanager;
            mInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return citymanager == null ? 0: citymanager.size();
        }

        @Override
        public Object getItem(int position) {
            return citymanager.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if(convertView == null){
                holder = new ViewHolder();
                convertView = mInflater.inflate(R.layout.view_city_manager, parent, false);
                holder.grid_city = (TextView) convertView.findViewById(R.id.grid_city);
                holder.grid_temp = (TextView) convertView.findViewById(R.id.grid_temp);
                holder.grid_weatherimage = (CHImageView) convertView.findViewById(R.id.grid_weatherimage);
                holder.grid_weather = (TextView) convertView.findViewById(R.id.grid_weather);
                holder.grid_set_normal = (Button) convertView.findViewById(R.id.grid_set_normal);
                holder.city_item_layout = (TextView) convertView.findViewById(R.id.city_item_layout);
                holder.grid_item_delete = (TextView) convertView.findViewById(R.id.grid_item_delete);
                convertView.setTag(holder);
            }else{
                holder = (ViewHolder) convertView.getTag();
            }

            final ViewHolder Holder = holder;
            holder.grid_item_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mDialog = new Dialog(context, android.R.style.Theme_DeviceDefault_Dialog_NoActionBar);
                    View  deleteview = LayoutInflater.from(context).inflate(R.layout.view_city_dialog, null);
                    TextView exit_text = (TextView)deleteview.findViewById(R.id.exitapp_text);
                    Button  leftBtn = (Button) deleteview.findViewById(R.id.leftbutton);
                    Button  rightBtn = (Button) deleteview.findViewById(R.id.rightbutton);
                    exit_text.setText("删除城市");
                    leftBtn.setText("确定");
                    rightBtn.setText("删除");
                    leftBtn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            SQLiteCityManager sqlite = new SQLiteCityManager(context, "weatherdb", null, 1);
                            SQLiteDatabase db = sqlite.getWritableDatabase();
                            String  mcityname = Holder.grid_city.getText().toString();
                            int index = db.delete("coolWeather", "cityname = ? ", new String[]{mcityname});
                            if(index == 0){
                                Toast.makeText(context, "删除失败，请重试", Toast.LENGTH_SHORT).show();
                            }
                            mDialog.dismiss();
                            for (int i = 0; i < citymanager.size(); i++){
                                if(mcityname.equals(citymanager.get(i).getCity())){
                                    citymanager.remove(i);
                                }
                            }
                            notifyDataSetChanged();
                        }
                    });

                    rightBtn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mDialog.dismiss();
                        }
                    });
                    mDialog.setContentView(deleteview);
                    mDialog.show();
                }
            });

            holder.grid_set_normal.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });

            if(position == citymanager.size() - 1){
                holder.grid_city.setText("");
                holder.grid_temp.setText("");
                holder.grid_weather.setText("");
                holder.grid_set_normal.setText("");
                holder.grid_weatherimage.setImageDrawable(null);
                holder.grid_set_normal.setBackgroundColor(Color.TRANSPARENT);
                holder.city_item_layout.setBackgroundResource(R.mipmap.cityadd_bg);
                holder.grid_item_delete.setText("");
            }else{
                holder.grid_item_delete.setText("x");
                holder.grid_city.setText(citymanager.get(position).getCity());
                holder.grid_temp.setText(citymanager.get(position).getTemp());
                holder.grid_weatherimage.loadImage(citymanager.get(position).getWeatherimage());
                holder.grid_weather.setText(citymanager.get(position).getWeather());
                holder.grid_set_normal.setBackgroundResource(R.drawable.select_city_normal_bg);
                if(position == 0){
                    holder.grid_set_normal.setText("默认");
                }else{
                    holder.grid_set_normal.setText("设为默认");
                }
                holder.city_item_layout.setBackgroundResource(Color.TRANSPARENT);
            }
            return convertView;
        }

        public void setCitymanager(List<CityManagerEntity> mcmb) {
            this.citymanager = mcmb;
        }

        public class ViewHolder{
            TextView  grid_city;
            TextView  grid_temp;
            CHImageView grid_weatherimage;
            TextView grid_weather;
            Button   grid_set_normal;
            TextView city_item_layout;
            TextView grid_item_delete;
        }
    }
}
